package com.sxj.corejava.code09_集合.map;

import java.util.*;

/**
 * @author 石小俊
 * @date 2025年02月20日
 */
public class Test02_遍历方式 {

    public static void main(String[] args) {
        Map<Integer, Student> students = new HashMap<>();
        Student student = new Student(1, "admin", 18);
        Student student2 = new Student(2, "jack", 19);
        Student student3 = new Student(3, "lucy", 20);
        Student student4 = new Student(4, "tom", 18);
        students.put(student.getId(), student);
        students.put(student2.getId(), student2);
        students.put(student3.getId(), student3);
        students.put(student4.getId(), student4);
//        test01(students);
//        test02(students);
        test03(students);
    }

    /**
     * 通过keySet()获取所有的key的集合, 然后遍历所有的key
     * 然后通过key可以获取到对应的value
     */
    public static void test01(Map<Integer, Student> students) {
        // 获取Map集合中所有key的集合,返回值是Set集合
        Set<Integer> set = students.keySet();
        for (Integer key : set) {
            // 根据key获取到对应的value
            Student student = students.get(key);
            System.out.println("key:" + key + ",value:" + student);
        }
    }

    /**
     * 通过values() 获取所有的value的集合, 然后遍历所有的value
     * 该方式无法获取key
     */
    public static void test02(Map<Integer, Student> students) {
        Collection<Student> values = students.values();
        for (Student student : values) {
            System.out.println(student);
        }
    }

    /**
     * 通过entrySet()获取所有的key-value的集合, 然后遍历所有的key-value键值对
     * Entry属于Map的内部类
     */
    public static void test03(Map<Integer, Student> students) {
        Set<Map.Entry<Integer, Student>> entries = students.entrySet();
        // 获取对应迭代器
        Iterator<Map.Entry<Integer, Student>> it = entries.iterator();
        while (it.hasNext()) {
            Map.Entry<Integer, Student> entry = it.next();
            // 通过entry可以获取到对应的key与value
            Integer key = entry.getKey();
            Student value = entry.getValue();
            System.out.println("key:" + key + ",value:" + value);
        }
    }

}
